package com.itheima.开启多线程.myrunnable;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 王加鑫
 * @Date 2021/5/24 15:09
 * @Version 1.0
 */
public class MyRunnableDemo01 {

    public static void main(String[] args) {
        SellTicket runnableTest = new SellTicket();
        Thread thread1 = new Thread(runnableTest);
        Thread thread2 = new Thread(runnableTest);
        Thread thread3 = new Thread(runnableTest);
        thread1.start();
        thread2.start();
        thread3.start();

    }
}

class SellTicket implements Runnable {

    //共享数据
    private static int ticket = 100;

    private Lock lock = new ReentrantLock();

    /* @Override
     public void run() {
         while (true){
             *//*
            同步代码块的方式 格式:
            synchronized {
                多条语句操作共享数据的代码
            }
             *//*
            synchronized ("abc"){
                if(ticket <= 0){
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                ticket--;
                System.out.println(Thread.currentThread().getName() + "正在卖票,还剩" + ticket + "张票");
            }
        }*/



    /*
    lock锁对象:多个线程必须使用同一把锁对象
     */
    @Override
    public void run() {
        //method();
        while (true) {
            try {
                lock.lock();
                if(ticket <= 0){
                    break;
                }
                Thread.sleep(100);
                ticket--;
                System.out.println(Thread.currentThread().getName() + "正在卖票,还剩" + ticket + "张票");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
    /*
    非静态同步方法: 锁对象为this(对象的引用)
    静态同步方法: 锁对象为类.class
     */
    private static synchronized void method() {
        while (true) {
            if (ticket <= 0) {
                break;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticket--;
            System.out.println(Thread.currentThread().getName() + "正在卖票,还剩" + ticket + "张票");
        }
    }
}
